/**
 * @author 王斌
 */
gameStart = function(){
	//场景的初始化
	var config = {
		width : 50,
		height : 40,
		incScore : 20,//吃食物时增加的分数
	}
	//蛇头的初始位置
	var X = 200;
	var Y = 200;
	//蛇的参数：颜色，头位置，方向
	//dir方向0左，1上，2右，3下
	var Snake = {
		color : "#52abad",
		position : [],
		dir : 0
	}
	//地图的数组，0没有，1有蛇，2有食物
	var map = [];
	for(var i=0;i<config.width;i++){
		map[i] = [];
	}
	map[20][20] = 1;
	var direction_x = [-1,0,1,0];
	var direction_y = [0,-1,0,1];
	var cvs = document.getElementById('playSpace');
	var ctx = cvs.getContext('2d');
	ctx.fillStyle = Snake.color;
	ctx.fillRect(X+1,Y+1,9,9);
//	ctx.fillRect(200, 200, 9, 9);
	var food_ran = function(){
		var x = parseInt(Math.random()*config.width)*10;
		var y = parseInt(Math.random()*config.height)*10;
		map[x/10][y/10] = 2;
		ctx.fillRect(x,y,8,8);
	}
	food_ran();
	var obj = {};
	obj.x = X;
	obj.y = Y;
	Snake.position.push(obj);
	var interval = setInterval(function(){
		snakeRun(Snake.dir);
	}, 200);
	var snakeRun = function(dire){
        var a = Snake.position.pop();
		map[a.x/10][a.y/10] = 0;
        ctx.clearRect(a.x, a.y, 10, 10);
        X = X + direction_x[dire] * 10;
        Y = Y + direction_y[dire] * 10;
        ctx.fillRect(X, Y, 9, 9);
        a.x = X;
        a.y = Y;
        Snake.position.unshift(a);
		if(X<0||Y<0||X>490||Y>390||map[X/10][Y/10]==1){
			alert("死亡");
			clearInterval(interval);
		}else{
			if(map[X/10][Y/10]==2){
				map[X/10][Y/10] = 1;
				food_ran();
				var a = {};
				X = X + direction_x[dire]*10;
				Y = Y + direction_y[dire]*10;
				ctx.fillRect(X,Y,9,9);
				a.x = X;
				a.y = Y;
				Snake.position.unshift(a);
			}		
		}
		map[a.x / 10][a.y / 10] = 1;
	}
	document.onkeydown = function(e){
		var keyNum = e.keyCode - 37;
		//键盘的事件
		if(keyNum<4&&keyNum>=0){
			Snake.dir = keyNum;
			snakeRun(keyNum);
		}
	}
}
